//
//  BaseTabBarController.swift
//  SwiftDeme
//
//  Created by apple on 2019/7/7.
//  Copyright © 2019 yimiSun. All rights reserved.
//

import UIKit

/**
 *  自定义系统底部导航
 */
class BaseTabBarController: UITabBarController {
    
    //MARK: - proterty
    private let bar_title_tag:Int = 111
    private let _unselectColor:UIColor = UIColor.init().colorFromHexInt(hex: 0xC6D0D9)
    
    /** 首页 */
    private lazy var _hmvc = MainViewController()

    /** 我的 */
    private lazy var _myvc = MineViewController()
    
    private lazy var offsetImageY = CGFloat.init(1)
    private lazy var offsetTitleY = CGFloat.init(-4)
    private lazy var tabBarButtons = NSMutableArray.init()
    private lazy var backingViewControllers = [UIViewController]()
    private lazy var scrollView:UIScrollView = {
        autoreleasepool {
            let _sv = UIScrollView.init(frame: self.view.bounds)
            _sv.isPagingEnabled = true
            _sv.bounces = false
            _sv.delegate = self
            
            return _sv
        }
    }()
    
    
    //MARK: - override func
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        //设置启动视图
        //self.setLaunchView()
        
        //指定委托
        self.delegate = self
        
        if UIDevice.current.isiPhoneX() {
            offsetTitleY = CGFloat.init(6)
            offsetImageY = CGFloat.init(-3)
        }
        
        //设置栏目
        let _arrViewControllers:[UIViewController] = [
            self.setViewControler(viewController: _hmvc, AndTitle: "首页", AndImage: "home.png", WithSelectImage: "home_hover.png"),
            self.setViewControler(viewController: _myvc, AndTitle: "我的", AndImage: "mine.png", WithSelectImage: "mine_hover.png"),
        ]
        self.setViewControllers(_arrViewControllers, animated: false)
        
        //清除顶部线
        Utils.shareInstance().clearnTabBarTopLine(tabBar: self.tabBar)
        
        //设置上阴影
        Utils.shareInstance().setViewShadowStyle(uView: self.tabBar,
                                                 shadowRadius: CGFloat.init(4),
                                                 shadowOffset: CGSize.init(width: 0, height: -0.8))
        
        //背景
        self.tabBar.backgroundColor = K_APP_VIEWCONTROLLER_BACKGROUND_COLOR
        //self.tabBar.backgroundImage = UIImage.init(named: "tabbar_bg.png")
        
        //选中背景
        //self.tabBar.selectionIndicatorImage = UIImage.init(named: "tabbar_select_bg.png")
        
        //添加滚动视图
        self.view.insertSubview(self.scrollView, belowSubview: self.tabBar)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        //设置高度
        Utils.shareInstance().setTabbarHeight(tabBar: self.tabBar)

        //设置tabBar信息
        self.setTabBarButtons()
    }
    
    override func setViewControllers(_ viewControllers: [UIViewController]?, animated: Bool) {
        super.setViewControllers(viewControllers, animated: animated)
        
        if viewControllers != nil {
            self.backingViewControllers = viewControllers!
            let size:CGSize = self.view.frame.size
            
            NSArray.init(array: viewControllers!).enumerateObjects {[unowned self] (_vc:Any, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) in
                if let _viewController = _vc as? UIViewController {
                    self.addChild(_viewController)
                    
                    _viewController.view.frame = CGRect.init(x: size.width * CGFloat(idx), y: 0,
                                                             width: size.width, height: size.height)
                    self.scrollView.addSubview(_viewController.view)
                }
            }
            
            self.scrollView.contentSize = CGSize.init(width: size.width * CGFloat(viewControllers!.count),
                                                      height: size.height)
        }
    }
    
    deinit {
        print("\(self.className()) 已销毁")
    }
    
}


//MARK: - extension
extension BaseTabBarController {
    
    /** 设置子视图 */
    private func setViewControler(viewController:UIViewController,
                                  AndTitle _title:String,
                                  AndImage _image:String,
                                  WithSelectImage _selectImage:String,
                                  AndTitleOffsetX _offsetX:CGFloat? = nil,
                                  AndImgOffsetY _offsetY:CGFloat? = nil) -> UIViewController {
        
        viewController.title = _title
        viewController.tabBarItem.titlePositionAdjustment = .init(horizontal: 0, vertical: offsetTitleY)
        if _offsetX != nil {
            viewController.tabBarItem.titlePositionAdjustment = .init(horizontal: _offsetX!, vertical: offsetTitleY)
        }

        viewController.tabBarItem.image = UIImage.init(named: _image)?.withRenderingMode(.alwaysOriginal)
        viewController.tabBarItem.selectedImage = UIImage.init(named: _selectImage)?.withRenderingMode(.alwaysOriginal)

        viewController.tabBarItem.imageInsets = UIEdgeInsets(top: -offsetImageY, left: 0, bottom: offsetImageY, right: 0)
        if _offsetY != nil {
            viewController.tabBarItem.imageInsets = UIEdgeInsets(top: _offsetY!, left: 0, bottom: -offsetImageY, right: 0)
        }
        
        //未选中的颜色
        viewController.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : _unselectColor], for: .normal)
        //选中颜色(默认与主题色一致)
        viewController.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : K_APP_TINT_COLOR], for: .selected)
        
        return viewController
    }
    
    /** 设置启动视图 */
    private func setLaunchView(){
        let _isFirst:Bool? = UserDefaults.standard.bool(forKey: K_APP_START_GUIDE_VIEW_HAS_KEY)
        if _isFirst == nil || _isFirst == false {
            
            DispatchQueue.global().async {
                //...
                
                DispatchQueue.main.async {
                    //...
                }
            }
        }
    }
    
    
    private func setTabBarButtons(){
        DispatchQueue.main.async {

            /**KVO 访问私有属性
             * _info/_imageView:UIImageView 就是显示的图片
             * _label:是UILabel 显示的文字
             * _badge:消息角标
             * _selected:选中状态
             */
            
            autoreleasepool {
                self.tabBarButtons = NSMutableArray.init(array: self.tabBar.subviews.filter({ return $0.isKind(of: NSClassFromString("UITabBarButton")!) }))
                
                self.tabBarButtons.enumerateObjects {[unowned self] (_tabBarButton:Any, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) in

                    if let tabBarButton = _tabBarButton as? UIView {
                        let isSelect:Bool = tabBarButton.value(forKey: "_selected") as? Bool ?? false

                        if let tabBarLabel = tabBarButton.value(forKeyPath: "_label") as? UILabel {
                            for _view in tabBarButton.subviews {
                                if let tabBarImageView:UIImageView = _view as? UIImageView {
                                    let imageView:UIImageView = UIImageView.init(frame: tabBarImageView.frame)
                                    imageView.alpha = 0
                                    imageView.image = isSelect ? self.backingViewControllers[idx].tabBarItem.image : self.backingViewControllers[idx].tabBarItem.selectedImage
                                    imageView.translatesAutoresizingMaskIntoConstraints = true
                                    tabBarButton.insertSubview(imageView, at:isSelect ? 1 : 0)

                                    //名称
                                    if isSelect {
                                        let label:UILabel = UILabel.init(frame: tabBarLabel.frame)
                                        label.alpha = 0
                                        label.textColor = _unselectColor
                                        label.font = tabBarLabel.font
                                        label.text = self.backingViewControllers[idx].tabBarItem.title
                                        label.translatesAutoresizingMaskIntoConstraints = true
                                        tabBarButton.insertSubview(label, at:isSelect ? 2 : 1)
                                    }
                                    else {
                                        let label:UILabel = UILabel.init(frame: tabBarLabel.frame)
                                        label.textColor = K_APP_TINT_COLOR
                                        label.alpha = 0
                                        label.font = tabBarLabel.font
                                        label.text = self.backingViewControllers[idx].tabBarItem.title
                                        label.translatesAutoresizingMaskIntoConstraints = true
                                        tabBarButton.insertSubview(label, at:isSelect ? 2 : 1)

                                        let label2:UILabel = UILabel.init(frame: tabBarLabel.frame)
                                        label2.tag = bar_title_tag
                                        label2.textColor = _unselectColor
                                        label2.font = tabBarLabel.font
                                        label2.text = self.backingViewControllers[idx].tabBarItem.title
                                        label2.translatesAutoresizingMaskIntoConstraints = true
                                        tabBarButton.insertSubview(label2, at:isSelect ? 3 : 2)
                                    }

                                    break
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    
    ///图标改变
    private func action(TabBarButton _tview:UIView,
                        andHighlighted h:Bool,
                        withDeltaAlpha deltaAlpha:CGFloat) {
        
        let _select:Bool = _tview.value(forKey: "_selected") as? Bool ?? false
        
        if h {
            for _view in _tview.subviews {
                if _view.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) ||
                    _view.isKind(of: NSClassFromString("UITabBarButtonLabel")!) ||
                    (_view.isKind(of: NSClassFromString("UILabel")!) && _view.tag == bar_title_tag) {
                    _view.alpha = _select ? 1 - deltaAlpha : deltaAlpha
                }
                else if _view.isKind(of: NSClassFromString("UIImageView")!) ||
                            (_view.isKind(of: NSClassFromString("UILabel")!) && _view.tag != bar_title_tag) {
                    _view.alpha = _select ? deltaAlpha : 1 - deltaAlpha
                }
            }
        }
        else{
            for _view in _tview.subviews {
                if _view.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) ||
                    _view.isKind(of: NSClassFromString("UITabBarButtonLabel")!) ||
                    (_view.isKind(of: NSClassFromString("UILabel")!) && _view.tag == bar_title_tag) {
                    _view.alpha = _select ? deltaAlpha : 1 - deltaAlpha
                }
                else if _view.isKind(of: NSClassFromString("UIImageView")!) ||
                            (_view.isKind(of: NSClassFromString("UILabel")!) && _view.tag != bar_title_tag) {
                    _view.alpha = _select ? 1 - deltaAlpha : deltaAlpha
                }
            }
        }
    }
    
    ///图标改变
    private func actionEndFor(CurrentIndex ci:Int) {
        
        if self.tabBarButtons.count > ci {
            self.tabBarButtons.enumerateObjects {[unowned self] (tabBarButton:Any, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) in
                if let _tview = tabBarButton as? UIView {
                    let _select:Bool = _tview.value(forKey: "_selected") as? Bool ?? false
                    
                    if idx == ci {
                        for _view in _tview.subviews {
                            if _view.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) ||
                                _view.isKind(of: NSClassFromString("UITabBarButtonLabel")!) ||
                                (_view.isKind(of: NSClassFromString("UILabel")!) && _view.tag == bar_title_tag) {
                                _view.alpha = _select ? 1 : 0
                            }
                            else if _view.isKind(of: NSClassFromString("UIImageView")!) ||
                                        (_view.isKind(of: NSClassFromString("UILabel")!) && _view.tag != bar_title_tag) {
                                _view.alpha = _select ? 0 : 1
                            }
                        }
                    }
                    else{
                        for _view in _tview.subviews {
                            if _view.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) ||
                                _view.isKind(of: NSClassFromString("UITabBarButtonLabel")!) ||
                                (_view.isKind(of: NSClassFromString("UILabel")!) && _view.tag == bar_title_tag) {
                                _view.alpha = _select ? 0 : 1
                            }
                            else if _view.isKind(of: NSClassFromString("UIImageView")!) ||
                                        (_view.isKind(of: NSClassFromString("UILabel")!) && _view.tag != bar_title_tag) {
                                _view.alpha = _select ? 1 :0
                            }
                        }
                    }
                }
            }
        }
    }
}


//MARK: - UITabBarControllerDelegate
extension BaseTabBarController : UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let _willToIndex:Int = tabBarController.children.firstIndex { return $0 == viewController }!
        
        if self.backingViewControllers.count > _willToIndex {
            let _size = self.view.frame.size
            self.scrollView.scrollRectToVisible(CGRect.init(x: CGFloat(_willToIndex) * _size.width, y: 0,
                                                            width: _size.width, height: _size.height), animated: true)
            //点击动画
            if self.tabBarButtons.count > _willToIndex {
                let tabBarButton:UIView? = self.tabBarButtons[_willToIndex] as? UIView

                let basicAnimation = CABasicAnimation(keyPath: "transform.scale")
                basicAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
                basicAnimation.duration = 0.08
                basicAnimation.repeatCount = 1
                basicAnimation.autoreverses = true
                basicAnimation.fromValue = NSNumber(value: 0.7)
                basicAnimation.toValue = NSNumber(value: 1.3)
                tabBarButton?.layer.add(basicAnimation, forKey: nil)
            }
        }
        return false
    }

    func tabBarControllerSupportedInterfaceOrientations(_ tabBarController: UITabBarController) -> UIInterfaceOrientationMask {
        return tabBarController.selectedViewController!.supportedInterfaceOrientations
    }

}


//MARK: - UIScrollViewDelegate
extension BaseTabBarController : UIScrollViewDelegate {
 
    //滑动中
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        let _w:CGFloat = self.view.frame.size.width
        let index = Int(scrollView.contentOffset.x / _w)

        let mod:CGFloat = fmod(scrollView.contentOffset.x,_w)
        let deltaAlpha:CGFloat = mod * (1.0 / _w)

        self.tabBarButtons.enumerateObjects {[unowned self] (tabBarButton:Any, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) in
            if let _view = tabBarButton as? UIView {
                if idx == index {
                    self.action(TabBarButton: _view,
                                andHighlighted: true,
                                withDeltaAlpha: deltaAlpha)
                }
                else if idx == index + 1 {
                    self.action(TabBarButton: _view,
                                andHighlighted: false,
                                withDeltaAlpha: deltaAlpha)
                }
            }
        }
    }
    
    //tabBar 点击触发
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        let _w:CGFloat = self.view.frame.size.width
        let index = Int(scrollView.contentOffset.x / _w)

        self.actionEndFor(CurrentIndex: index)
    }

}
